package com.ruoyan.controller;

import com.google.code.kaptcha.Constants;
import com.ruoyan.pojo.User;
import com.ruoyan.service.UserService;
import com.ruoyan.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Package: com.ruoyan.controller
 * @ClassName: LoginController
 * @Author: ruoyan1998
 * @CreateTime: 2021/5/16 14:13
 * @Description:
 */
@Controller
public class LoginController
{
    @Autowired
    private UserService userService;

    /**
     * 管理员登录实现*/
    @PostMapping( "/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model, HttpSession session,HttpServletRequest code)
    {
        User user = userService.queryUserByNameAndPassword(username, password);

        if (null == user)
        {
            model.addAttribute("msg", "账户名或密码错误，请重新登录！");
            return "index";
        }
        else if(!CaptchaUtil.checkVerifyCode(code))
        {
            model.addAttribute("msg","验证码有误，请重新登录!");
            return "index";
        }
        else
        {
            session.setAttribute("user", user);
        }

        return "redirect:/dashboard";
    }
}
